#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
任务模型
"""

from sqlalchemy import Column, Integer, String, Enum, Text, DateTime, Boolean, ForeignKey, BigInteger
import json
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.core.database import Base
import enum

class TaskType(enum.Enum):
    """任务类型枚举"""
    RECORD = "record"          # 录制
    PUSH = "push"             # 转推
    TRANSCODE = "transcode"    # 转码
    CLIP = "clip"             # 拆条

class TaskStatus(enum.Enum):
    """任务状态枚举"""
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELLED = "cancelled"
    ERROR = "error"

class PushProtocol(enum.Enum):
    """转推协议枚举"""
    RTMP = "rtmp"
    HLS = "hls"

class Task(Base):
    __tablename__ = "tasks"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, comment="任务名称")
    task_type = Column(String(50), nullable=False, comment="任务类型")
    status = Column(Enum(TaskStatus, values_callable=lambda x: [e.value for e in x]), default=TaskStatus.PENDING, comment="任务状态")
    
    # 关联流
    stream_id = Column(Integer, ForeignKey("streams.id"), nullable=False, comment="关联流ID")
    stream = relationship("Stream", backref="tasks")
    
    # 任务配置
    config = Column(Text, default=None, comment="任务配置 - 直接存储FFmpeg命令行字符串")
    
    # 录制配置
    record_path = Column(String(500), nullable=True, comment="录制文件路径")
    record_duration = Column(Integer, nullable=True, comment="录制时长(秒)")
    segment_duration = Column(Integer, default=3600, comment="分段时长(秒)")
    
    # 转推配置
    push_url = Column(String(500), nullable=True, comment="转推地址")
    push_key = Column(String(100), nullable=True, comment="转推密钥")
    
    # 转码配置
    tempid = Column(String(10), nullable=True, comment="转码模板ID")
    transcode_url = Column(String(500), nullable=True, comment="转码输出地址，格式为rtmp地址;url地址")
    
    # 状态信息
    pid = Column(Integer, nullable=True, comment="进程ID")
    progress = Column(Integer, default=0, comment="进度百分比")
    error_message = Column(Text, nullable=True, comment="错误信息")
    
    # 文件信息
    output_path = Column(String(500), nullable=True, comment="输出路径")
    file_size = Column(BigInteger, default=0, comment="文件大小(字节)")
    
    # 重试机制
    retry_count = Column(Integer, default=0, comment="重试次数")
    max_retries = Column(Integer, default=3, comment="最大重试次数")
    last_error = Column(Text, nullable=True, comment="最后错误信息")
    
    # 软删除标志
    inuse = Column(Integer, default=1, comment="是否使用中 1=使用中 0=已删除")
    
    # 扩展信息
    info = Column(Text, nullable=True, comment="扩展信息(JSON格式)")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    started_at = Column(DateTime(timezone=True), nullable=True, comment="开始时间")
    completed_at = Column(DateTime(timezone=True), nullable=True, comment="完成时间")
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    def __repr__(self):
        return f"<Task(id={self.id}, name={self.name}, type={self.task_type}, status={self.status})>"
    
    def to_dict(self):
        # 直接返回config原始字符串，不进行JSON解析
        return {
            "id": self.id,
            "name": self.name,
            "task_type": self.task_type,
            "status": self.status.value,
            "stream_id": self.stream_id,
            "config": self.config,
            "record_path": self.record_path,
            "record_duration": self.record_duration,
            "segment_duration": self.segment_duration,
            "push_url": self.push_url,
            "push_key": self.push_key,
            "tempid": self.tempid,
            "transcode_url": self.transcode_url,
            "pid": self.pid,
            "progress": self.progress,
            "error_message": self.error_message,
            "output_path": self.output_path,
            "file_size": self.file_size,
            "retry_count": self.retry_count,
            "max_retries": self.max_retries,
            "last_error": self.last_error,
            "inuse": self.inuse,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "started_at": self.started_at.isoformat() if self.started_at else None,
            "completed_at": self.completed_at.isoformat() if self.completed_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }